package databasetest;

import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.util.Vector;

import javax.swing.JInternalFrame;
import javax.swing.JPanel;

import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JLabel;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;

public class Select extends JInternalFrame {
	Connection conn;
	DatabaseTest dt;
	private JPanel panel;
	private JButton btnNewButton;
	private JTextField textField;
	private JScrollPane scrollPane;
	private JTable table;


	Statement stmt = null;
	DefaultTableModel model;
	private JLabel status;
	
	

	public Select(Connection conn2, DatabaseTest d) {
		super("조회", true, true, true, false);
		this.dt = d;
		this.conn = conn2;
		
		
		addInternalFrameListener(new InternalFrameAdapter() { // 조회 인터널프레임 종료했을때	// 초기화시키는 부분
			@Override
			public void internalFrameClosing(InternalFrameEvent e) { // 클로징 이벤트
				if (model != null) {
					model.setRowCount(0);
					model.setColumnCount(0);
				}
				textField.setText("");
			}
		}
		);

		setBounds(500, 350, 450, 300);
		getContentPane().add(getPanel(), BorderLayout.NORTH);
		getContentPane().add(getScrollPane(), BorderLayout.CENTER);
		getContentPane().add(getStatus(), BorderLayout.SOUTH);
		textField.setText("select*from ptbl");

	}

	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setLayout(new BorderLayout(0, 0));
			panel.add(getBtnNewButton(), BorderLayout.EAST);
			panel.add(getTextField(), BorderLayout.CENTER);
		}
		return panel;
	}

	private JButton getBtnNewButton() {
		if (btnNewButton == null) {
			btnNewButton = new JButton("쿼리실행");
			btnNewButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					setList();
				}
			});
		}
		return btnNewButton;
	}

	public void setList() {
		String sql = textField.getText();
		try {
			PreparedStatement pstmt = conn.prepareStatement(sql);
			ResultSet rs = pstmt.executeQuery();
			// //-------------------------------------------------------------------------------	// 컬럼명 얻어오기.
			ResultSetMetaData rsmd = null;
			rsmd = rs.getMetaData();
			Vector<String> col = new Vector<String>();
			int colCount = rsmd.getColumnCount(); // 컬럼의 개수
			col.add("NO") ;
			for (int i = 1; i <= colCount; i++) {
				String colname = rsmd.getColumnName(i); // 컬럼 이름을 콜네임에 입력
				col.add(colname);
			}
			model = new DefaultTableModel(col, 0); // 컬럼을 추가						
			// ------------------------------------------------------------------------------------------데이터값	// 얻어오기.		
			 DecimalFormat df = new DecimalFormat("#,###");
			int cnt=1;
			while (rs.next()) {				
				Vector  vec = new Vector <>();
				vec.add(cnt);				
				for (int i = 1; i <= colCount; i++) { // 컬럼의 길이까지					
					vec.add(rs.getString(i)); // 1,2,3, i 번째 컬럼의 데이터값 가져오기					
				}
				model.addRow(vec); // 한줄 완성-->로우 추가
				cnt++;
			}
			table.setModel(model);
			rs.close();
			pstmt.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private JTextField getTextField() {
		if (textField == null) {
			textField = new JTextField();
			textField.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent e) {
					if (e.getKeyCode() == KeyEvent.VK_ENTER) {
						setList();
					}
				}
			});
			textField.setColumns(10);
		}
		return textField;
	}

	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();			
			scrollPane.setViewportView(getTable()); // 컬럼 추가후에 추가 ㅎ
		}
		return scrollPane;
	}

	private JTable getTable() {
		if (table == null) {
			table = new JTable(model);

			table.addMouseListener(new MouseAdapter() {
				@Override
				public void mousePressed(MouseEvent e) {
					
					if(dt.update==null) dt.openUpdate();				

					int index = table.getSelectedRow();// 선택된 열의 table index번호를저장
					String serial= (String)model.getValueAt(index, 1);
					String code =(String)model.getValueAt(index, 2);
					String ea =(String)model.getValueAt(index, 3);				
					
					dt.update.setData(serial,code,ea);
					dt.update.setVisible(true);
					dt.update.toFront();					
					
					

				}
			});

		}
		return table;
	}

	private JLabel getStatus() {
		if (status == null) {
			status = new JLabel("New label");
		}
		return status;
	}
}
